<template>
<div style="margin-top:20px">
    <Row :gutter="16">
        <Col :md="6">
        <Form ref="EditForm" :model="FormData" label-position="top">
            <Row :gutter="16">
                <Col>
                <FormItem label="套餐名称" prop="RuleName" :rules="{required: true, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="FormData.RuleName"></Input>
                </FormItem>
                </Col>

                <Col>
                <FormItem label="备注信息" prop="RuleInfo" :rules="{required: false, message:'不能为空', trigger: 'blur'}">
                    <Input v-model="FormData.RuleInfo"></Input>
                </FormItem>
                </Col>

                 <Col>
                     <FormItem label="可见字典表设置" prop="RuleDict" :rules="{required: true, type: 'array', message:'不能为空', trigger: 'change'}">
                         <DictSelect :multiple="true"  v-model="FormData.RuleDict"  label=""  placeholder='请选择'></DictSelect>
                     </FormItem>

                </Col>


                <Col>
                <FormItem label="所属系统" prop="RulePlatformID" :rules="{required: true,type:'number', message:'不能为空', trigger: 'change'}">
                    <Select v-model="FormData.RulePlatformID" clearable>
                         <Option v-for="item in PlatformItems" :value="item.value" :key="item.value">{{ item.label }}</Option>
                    </Select>
                </FormItem>
                </Col>


                <Col>
                <FormItem>
                    <Button type="primary" @click="handleSubmit()">提交</Button>
                    <Button   @click="handleReset()" style="margin-left: 8px">重置</Button>
                </FormItem>
                </Col>


            </Row>
        </Form>
        </Col>
        <Col :md="18">
        <div id="SystemModules" style="font-size:12px"></div>
        </Col>
    </Row>
    <Modal v-model="SelectDataOptionsWin.IsShow" :loading="SelectDataOptionsWin.IsLoading" title="设置数据可见程度" @on-ok="SelectDataOptionsWin.OkEvent" @on-cancel="SelectDataOptionsWin.CancelEvent">
        <Row :gutter="16">
            <Col :xs="24" :md="24">
            <CheckboxGroup vertical v-model="SelectDataOptionsWin.Result" size="large">
                <Checkbox v-for="item in SelectDataOptionsWin.Data" :key="item.name" :label="item.label"></Checkbox>
            </CheckboxGroup>
            </Col>
        </Row>
    </Modal>
</div>
</template>

<script>
import then from 'thenjs';
import moment from 'moment';
import AppFrame from '../../../libs/app-frame';
import TreeSelect from '../../../components/tree-select';
import DictSelect from '../../../components/dict-select'
export default {
    components: {
        TreeSelect,
        DictSelect
    },
    data: function() {
        let self = this;
        let SelectDataOptionsWin = {
            IsShow: false,
            IsLoading: false,
            Data: [],
            Result: [],
            TargetElment: {},
            e: {},
            OkEvent: function() {
                let selectDataOptions=[];
                alert(JSON.stringify( SelectDataOptionsWin.Result));
                SelectDataOptionsWin.Result.map(function(label) {
                    let selectOption = SelectDataOptionsWin.Data.find((item) => {
                        return item.label == label;
                    });
                    selectDataOptions.push(selectOption);
                });

                SelectDataOptionsWin.TargetElment.attr("data-res", encodeURI(JSON.stringify(selectDataOptions)));
                SelectDataOptionsWin.TargetElment.text("数据范围:已设置(" + selectDataOptions.length+")");
                self.AbleEvent(SelectDataOptionsWin.e, SelectDataOptionsWin.TargetElment);
            },
            CancelEvent: function() {}
        };
        return {
            SelectNodeIsSelectAllAbel: true,
            State: { //数据加载状态
                IsLoadingData: false,
                IsChangeData: false
            },
            SelectDataOptionsWin: SelectDataOptionsWin,
            SysModules: [],
            TreeData: [],
            CurSelectNode: {},

            UserRuleAbles: [],
            PlatformItems: [],
             DataDegree:[],
            FormData: {
                RuleID: 0,
                RuleInfo: '',
                RulePlatformID: 0,
                RuleName: '',
                RuleAble: '',
                RuleDict:[]

            },
            Query: {},

        }
    },
    created: function() {
        let self = this;
        this.Query = this.$route.query;
        this.getFormData();
    },
    watch: {
        '$route': function() { //当路由改变时
            this.Query = this.$route.query;
            this.getFormData();
        }
    },

    mounted: function() {
        let self = this;
        $("#SystemModules").delegate(".ableItem", "click", function(e) {
            e.stopPropagation(); //阻止冒泡
            var state = $(this).attr("data-state");
            self.AbleEvent(e, $(this));
        });

        $("#SystemModules").delegate(".dataOptionItem", "click", function(e) {
            e.stopPropagation(); //阻止冒泡
            let CurModuleID = $(this).attr("data-id");
            let CurSelectedDataOption = decodeURI($(this).attr("data-res"));

            let module = self.SysModules.find((item) => {
                return item.ModuleID == CurModuleID
            });
            if (CurSelectedDataOption && CurSelectedDataOption != '') {

                CurSelectedDataOption = JSON.parse(CurSelectedDataOption);
                self.SelectDataOptionsWin.Result.splice(0,self.SelectDataOptionsWin.Result.length);
                CurSelectedDataOption.map(function(item){
                    self.SelectDataOptionsWin.Result.push(item.label);
                })

            }

            self.SelectDataOptionsWin.TargetElment = $(this);
            self.SelectDataOptionsWin.Data = JSON.parse(module.DataOptions);
            self.SelectDataOptionsWin.IsShow = true;
            self.SelectDataOptionsWin.e = e;


        });


    },

    methods: {
        getFormData: function() {
            let self = this;
            self.State.IsLoadingData = true;
            let postData = {
                RuleID: self.Query.RuleID || 0,
            };
            AppFrame.Http.Post("/manage-api/system/platform-rule/getItem", postData, function(err, ret) {
                self.State.IsLoadingData = false;
                if (ret && ret.Result == 1) {
                    self.SysModules = ret.Data.SysModules;
                    self.UserRuleAbles =ret.Data.Model? ret.Data.Model.RuleAble:[];
                    self. DataDegree=ret.Data.DataDegreeItems;
                    ret.Data.PlatformItems.map(function(item) {
                        self.PlatformItems.push({
                            label: item.IP_Name,
                            value: item.IP_ID
                        })
                    })
                    self.FormData = ret.Data.Model;

                    let RuleDict=ret.Data.Model.RuleDict?JSON.parse(ret.Data.Model.RuleDict):[];
                    let _ipDict=[];
                    for(var i in RuleDict){
                        if(RuleDict[i]){
                            RuleDict[i].map(function(it){
                                _ipDict.push(`${i}-${it}`);
                            })
                        }
                    }

                     self.FormData.RuleDict=_ipDict;
                    console.log(self.FormData);
                    self.renderTree();
                }
            });
        },
        handleSubmit: function() {
            let self = this;
            this.$refs["EditForm"].validate((valid) => {
                if (valid) {
                    var treeval = window._Ables;
                    self.FormData.RuleAble = JSON.stringify(treeval);
                   //self.FormData.RuleDataDegreeCode=self.FormData.RuleDataDegreeCode.join(',');
                    let RuleDict={};
                    self.FormData.RuleDict.map(function(item){

                        let _it=item.split('-');
                         if(!RuleDict[_it[0]]){
                             RuleDict[_it[0]]=[];
                         }
                        RuleDict[_it[0]].push(_it[1]);
                    });
                    self.FormData.RuleDict=JSON.stringify(RuleDict);
                    console.log(self.FormData);

                    AppFrame.Http.Post("/manage-api/system/platform-rule/edit", self.FormData, function(err, ret) {

                       if (ret && ret.Result == 1) {
                            self.$Message.success('保存成功');
                            self.$router.go(-1);
                        } else {
                            self.$Message.error(ret.Msg);
                        }
                    })
                }
            });

        },

        handleReset: function() {
            this.$refs["EditForm"].resetFields();
            this.$store.state.MsgBus.$emit('aaaa', 1);
            $(".ableItem").click(function() {
                //alert(1);
            })
        },

        GetTreeData() {

            let self = this;
            var _TreeData = [];
            _TreeData.push({
                id: 0,
                text: "系统模块",
                parent: "#",
                icon: "fa fa-folder",
                state: {
                    opened: true
                }
            });
            for (var i = 0; i < self.SysModules.length; i++) {
                var Node = this.GetNodeData(self.SysModules[i]);
                _TreeData.push(Node);
            };
            this.TreeData = _TreeData;
            return _TreeData;
        },

        GetNodeData(Module) {
            let self = this;
            var Node = {
                id: Module.ModuleID,
                parent: Module.ParentID,
                text: Module.Name,
                type: Module.IsParent == 1 ? "parent" : "children",
                a_attr: { //自定义a标签的属性
                    ModuleID: Module.ModuleID,
                    Name: Module.Name,
                    ParentID: Module.ParentID,
                    IsParent: Module.IsParent,
                    Icon: Module.Icon,
                    RoleIDs: Module.RoleIDs,
                    Sort: Module.RoleIDs,
                    URL: Module.URL,
                    Able: Module.Able,
                    SelectAble: "",
                    DataOptions: Module.DataOptions,
                    SelectDataOptions: [],
                    IsShowInMenu: Module.IsShowInMenu
                },
                state: {
                    opened: true
                }
            };
            var DefaultAble = "";
            for (var j = 0; j < self.UserRuleAbles.length; j++) {
                if (self.UserRuleAbles[j].M == Module.ModuleID) {
                    DefaultAble = self.UserRuleAbles[j].A;
                    break;
                }
            };

            var Able = "",
                DataOptions = "";
            if (self.FormData.RuleAble && typeof self.FormData.RuleAble == 'string') {
                self.FormData.RuleAble = JSON.parse(self.FormData.RuleAble);
            };
            var PlatFormModules = self.FormData.RuleAble;
            if (PlatFormModules && PlatFormModules instanceof Array && PlatFormModules.length > 0) {
                for (var j = 0; j < PlatFormModules.length; j++) {
                    if (PlatFormModules[j].M == Module.ModuleID) {
                        Able = PlatFormModules[j].A;
                        DataOptions = PlatFormModules[j].D;
                        break;
                    }
                }
            };
            if (Module.DataOptions && Module.DataOptions.length > 0) {
                if (DataOptions) {
                    //Node.a_attr.SelectDataOptions=DataOptions;
                    Node.text += '<a data-id="' + Module.ModuleID + '" data-res="' + encodeURI(JSON.stringify(DataOptions)) + '" class="margin-left-10 dataOptionItem">数据范围:已设置数量(' + DataOptions.length + ')</a>';
                } else {
                    Node.text += '<a data-id="' + Module.ModuleID + '" data-res="" class="margin-left-10 dataOptionItem">设置数据范围</a>';
                }

            }
            if (Module.Able != "") {
                var AbleArray = Module.Able.split(" ");
                for (var i in AbleArray) {
                    if (AbleArray[i] == "") continue;
                    if (DefaultAble.indexOf(AbleArray[i]) > -1) {
                        // Node.text += '<span class="ableItem margin-left-20 " data-val="' + AbleArray[i] + '" onclick="return false;"><i class="check fa fa-square-o fa-check-square "></i>' + AbleArray[i] + '</span>';
                    } else {
                        if (Able.indexOf(AbleArray[i]) > -1) {
                            Node.text += '<span class="ableItem margin-left-10 " data-state="1" data-val="' + AbleArray[i] + '"><i class="check fa  fa-square-o fa-check-square "></i>' + AbleArray[i] + '</span>';

                        } else {
                            Node.text += '<span class="ableItem margin-left-10" data-state="0" data-val="' + AbleArray[i] + '" ><i class="check fa fa-square-o"></i>' + AbleArray[i] + '</span>';
                        }
                    }

                }
            };

            return Node;
        },

        AbleEvent(event, obj, state) {
            let self = this;
            event.stopPropagation(); //阻止冒泡
            var target = event.target;
            var tagName = target.tagName;
            var checkbox = obj.find(".check");
            //-----------------
            var selectable_array = [];
            var UnCheckedCount = 0;
            //--------------
            var CurNode = {};
            var id = obj.parent().attr("moduleid");
            for (var i = 0; i < self.TreeData.length; i++) {
                var node = self.TreeData[i];
                if (node.id == id) {
                    CurNode = node;
                    break;
                }
            }
            //-------------
            if (state != undefined) {
                if (state == 1) {
                    obj.attr("checked", true);
                    checkbox.addClass(" fa-check-square");
                } else {
                    obj.attr("checked", false);
                    checkbox.removeClass(" fa-check-square");
                }

            } else {
                if (obj.attr("checked") == "checked") {
                    //取消选中
                    obj.attr("checked", false);
                    checkbox.removeClass(" fa-check-square");
                } else {
                    //选中
                    obj.attr("checked", true);
                    checkbox.addClass(" fa-check-square");
                    var t = $.jstree.reference('#SystemModules');
                    t.select_node(CurNode);
                }
            }
            //-------------------
            obj.parent().find(".ableItem").each(function() {
                if ($(this).attr("checked") == "checked") {
                    selectable_array.push($(this).attr("data-val"));
                } else {
                    UnCheckedCount++;
                }
            });
            //---------
            let selectDataOptions = [];

            if (obj.parent().find(".dataOptionItem").length > 0) {
                let dataOptionItemobj = obj.parent().find(".dataOptionItem");
                if (dataOptionItemobj.attr('data-res') != "") {
                    selectDataOptions = JSON.parse(decodeURI(dataOptionItemobj.attr('data-res')));

              }

            }
            obj.parent().attr("selectable", selectable_array.join(","));
            var NodeID = obj.parent().attr("moduleid");

            for (var i = 0; i < self.TreeData.length; i++) {
                var node = self.TreeData[i];
                if (node.id == NodeID) {
                    node.a_attr.SelectAble = selectable_array.join(",");
                    node.a_attr.SelectDataOptions = selectDataOptions;
                    break;
                }
            }
            self.GetCheckedItems();
        },

        GetCheckedItems: function() {
            var tree = $.jstree.reference('#SystemModules');
            var Ables = [];
            var self = this;

            function GetAbles(NodeID) {
                (function(NodeID) {
                    if (NodeID == 0) return;
                    for (var i = 0; i < self.TreeData.length; i++) {

                        if (self.TreeData[i].id == Number(NodeID)) {
                            var IsHave = false;
                            for (var c = 0; c < Ables.length; c++) {
                                if (Ables[c].M == self.TreeData[i].id) {
                                    IsHave = true;
                                    break;
                                }
                            }
                            //console.log(TreeData[i]);
                            if (!IsHave) {
                                var Able = {
                                    M: self.TreeData[i].id,
                                    A: self.TreeData[i].a_attr.SelectAble,
                                    D: self.TreeData[i].a_attr.SelectDataOptions
                                };
                                //console.log('Able',JSON.stringify(Able));
                                Ables.push(Able);
                            }
                            GetAbles(self.TreeData[i].parent);
                            break;
                        }
                    }
                })(NodeID);
            }


            var IDS = [];
            var nodes = tree.get_selected();
            $.each(nodes, function(i, n) {
                (function(id) {
                    GetAbles(id);
                })(nodes[i]);

            });
            window._Ables = Ables;
            //self.Ables=Ables;
            //console.log('Ables',Ables);
            return Ables;
        },

        FixTreeNodeCheckState() {

            let self = this;
            if (!self.FormData) return;
            var str = self.FormData.RuleAble ? self.FormData.RuleAble : null; //$("input[name='RuleAble']").val();
            var tree = $.jstree.reference('#SystemModules');
            if (str && str != "") {
                var CurRuleAble = str;

                window._Ables = CurRuleAble;
                if (typeof str == "string") {
                    CurRuleAble = JSON.parse(str);

                }

                //console.log('TreeData:',JSON.stringify(self.MainData.TreeData));
                for (var i = 0; i < CurRuleAble.length; i++) {
                    (function(i) {
                        var able = CurRuleAble[i];

                        var Node = $("#SystemModules").find("[moduleid=" + able.M + "]");
                        setTimeout(function() {
                            for (var i = 0; i < self.TreeData.length; i++) {
                                if (self.TreeData[i].id == Number(able.M) && self.TreeData[i].a_attr.IsParent == 0) {
                                    // console.log('id:',self.TreeData[i].id);
                                    self.TreeData[i].a_attr.SelectAble = able.A;
                                    self.TreeData[i].a_attr.SelectDataOptions=able.D;
                                    self.TreeData[i].state.selected = true;

                                    tree.select_node([self.TreeData[i]]);

                                    //console.log('self.TreeData[i]',self.TreeData[i]);
                                    break;
                                }
                            }
                            //  Node.addClass("jstree-clicked");
                            Node.attr("selectable", able.A);
                            Node.find(".ableItem").each(function() {
                                var self = $(this);
                                if (able.A.indexOf($(this).attr("data-val")) > -1) {
                                    self.attr("checked", true);
                                    self.find(".check").addClass("fa-check-square");
                                }
                            })
                        }, 0);
                    })(i);


                }
            }
        },

        renderTree: function() {
            let self = this;
            /**初始化JsTree */
            function InitSystemModules() {
                let tree = null;

                function initJsTree(TreeData) {
                    // console.log(TreeData);
                    $("#SystemModules").on("select_node.jstree", function(e, data) {
                        self.CurSelectNode = data.node;

                    });

                    $("#SystemModules").on("open_node.jstree", function(event, data) {
                        var nodeObj = $("#SystemModules").find("#" + data.node.li_attr.id);
                        // console.log(data);

                        nodeObj.find("a").each(function() {
                            var moduleID = $(this).attr("moduleid");

                            for (var i = 0; i < self.TreeData.length; i++) {
                                var node = self.TreeData[i];
                                if (node.id == moduleID) {
                                    $(this).attr("selectable", node.a_attr.SelectAble);
                                    $(this).find(".ableItem").each(function() {
                                        if (node.a_attr.SelectAble.indexOf($(this).attr("data-val")) > -1) {

                                            $(this).attr("checked", true);
                                            $(this).find(".check").addClass(" fa-check-square");
                                        }
                                    })
                                    break;
                                }
                            }
                        });

                    });

                    $("#SystemModules").on("changed.jstree", function(e, data) {
                        if (!data || !data.node || !data.node.li_attr) return;
                        if (!self.SelectNodeIsSelectAllAbel) return;
                        var nodeObj = $("#SystemModules").find("#" + data.node.li_attr.id);

                        if (data.action == "select_node") {

                        } else {
                            nodeObj.find("a").find(".ableItem").each(function() {
                                self.AbleEvent(e, $(this), 0);
                            })
                            setTimeout(function() {
                                var ParentID = data.node.a_attr.ParentID;
                                var parentObj = $("#SystemModules").find("a[moduleid='" + ParentID + "']");
                                if (parentObj.find(".jstree-undetermined").length == 0) {
                                    parentObj.find(".ableItem").each(function() {
                                        self.AbleEvent(e, $(this), 0);
                                    })
                                }
                            }, 80);

                        }
                        self.GetCheckedItems();
                    });



                    $("#SystemModules").jstree({
                        "core": {
                            "expand_selected_onload": true,
                            "multiple": true,
                            "themes": {
                                "variant": "large",
                                "responsive": false,
                            },
                            // so that create works
                            "check_callback": true,
                            'data': TreeData
                        },
                        "checkbox": {
                            "keep_selected_style": false
                        },
                        "types": {
                            "default": {
                                "icon": " fa fa-link"
                            },
                            "parent": {
                                "icon": " fa fa-bookmark"
                            }
                        },
                        "plugins": ["wholerow", "checkbox", "dnd", "types"],


                    });
                    tree = $.jstree.reference('#SystemModules');

                };

                var TreeData = self.GetTreeData();
                initJsTree(TreeData);

            };

            setTimeout(function() {
                InitSystemModules();
                setTimeout(function() {
                    self.FixTreeNodeCheckState();
                }, 500);
            }, 100);

        }


    }
}
</script>

<style scoped>

</style>
